package handler

import (
	"encoding/json"
	"romance-reads/cache"
	"romance-reads/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Detail(c *gin.Context) {
	id := c.Query("id")
	var con []models.Content
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&con)
		jsonData, _ := json.Marshal(con)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &con)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": con,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var con []models.Content
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&con)
		jsonData, _ := json.Marshal(con)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &con)
	}
	var total int64
	models.DB.Model(&models.Content{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  con,
		"total": total,
	})
	return
}
